<?php

require_once 'Basic.php';

class ModelCreate extends BasicEntity {

  private static $actionName = "Create";
  
  private static $brandField = "brand";
  private static $nameField = "name";
  private static $categoryField = "category";
  private static $diarypriceField = "diaryprice";
  private static $kmpriceField = "kmprice";
  private static $modelTypeField = "modelType";
  private static $loadField = "load";
  private static $stockingField = "stocking";
  
  private static $category = array(
      "B" => "B",
      "C" => "C",
      "D" => "D",
      "E" => "E",
      "A" => "A",
  );
  
  private $modelTypes;
  private $idUtilitario;
  
  public function __construct() {
  
    $db = new DBUtils;
    
    try {
      $db->connect();
 
      $this->modelTypes = array();
      $db->runQuery("select idTipoModelo,nome,subtipo from TipoModelo");
      for($item = $db->getItem(); $item !== null; $item = $db->getItem()) {
        if($item->subtipo === "utilitario") {
          $this->idUtilitario = $item->idTipoModelo;
        }
        $this->modelTypes[$item->idTipoModelo] = $item->nome;
      }
          
      $db->close(true);
    }
    catch(DBError $e) {
      $db->close(false);
      logMessage($e->errors, "DBError");
      return "Falha no banco de dados. O erro foi reportado.";
    }          
   
    $this->fields = array(
        new FormField(true, ModelCreate::$brandField, "Marca", new FormFieldTextLine()),
        new FormField(true, ModelCreate::$nameField, "Nome", new FormFieldTextLine()),
        new FormField(true, ModelCreate::$categoryField, "Categoria", new FormFieldChoice(ModelCreate::$category)),
        new FormField(true, ModelCreate::$diarypriceField, "Pre&ccedil;o da Di&aacute;ria", new FormFieldPrice(false)),
        new FormField(true, ModelCreate::$kmpriceField, "Pre&ccedil;o por KM", new FormFieldPrice(false)),        
        new FormField(true, ModelCreate::$modelTypeField, "Tipo", new FormFieldChoice($this->modelTypes)),
        new FormField(false, ModelCreate::$loadField, "Carga", new FormFieldAbsNumber()),
        new FormField(false, ModelCreate::$stockingField, "Lota&ccedil;&atilde;o", new FormFieldAbsNumber())
    );
    $this->processFields();
  }
  
  public function actionDescription() {
    return ModelCreate::$actionName;
  }
  
  public function actionCreate() {
		foreach($this->fields as $k => $v) {
		  $$k = $v->value();
		}
		
    $modelType = intval($modelType);
    if($load !== null) {
      $load = intval($load);
    }
    if($stocking !== null) {
      $stocking = intval($stocking);
    }
    $diaryprice = str_replace(",",".",$diaryprice);
    $kmprice = str_replace(",",".",$kmprice);
  
    if($this->idUtilitario === $modelType && $load === null && $stocking === null) {
      $out = "O modelo foi escolhido como utilit&aacute;rio. Favor digitar a carga e/ou a lota&ccedil;&atilde;o.";
      goto utilError;
    }
    else if($this->idUtilitario !== $modelType && ($load !== null || $stocking !== null)) {
      $out = htmlentities("Apenas modelos to tipo utilitário podem ter carga e/ou lotação.");
      goto utilError;
    }
  
		$db = new DBUtils();
		 
		try {
     $db->connect();
     $db->beginTransaction();
     $db->runQuery("select idModelo from Modelo where nome = ?", array($name));
     if($db->getItem() !== null) {
        $this->fields[ModelCreate::$nameField]->setValid(false);
        return "Modelo com nome ${name} j&aacute; cadastrado.";
     }
     
     $db->runQuery("insert into Modelo (marca, nome, categoria, precoDiaria, precoKm, tipoModelo) values(?, ?, ?, ?, ?, ?)",
                    array($brand, $name, $category, $diaryprice, $kmprice, intval($modelType)));
                    
     $db->runQuery("select idModelo from Modelo where nome = ?", array($name));
     $idModelo = $db->getItem()->idModelo;
     if($this->idUtilitario === $modelType){
       $db->runQuery("insert into ModeloUtilitario (idTipoModelo, idModelo, carga, lotacao) values(?, ?, ?, ?)",
               array($modelType, $idModelo, $load, $stocking));
     }
     
     $db->close(true);
    }
    catch(DBError $e) {
     $db->close(false);
     logMessage($e->errors, "ModelCreate");
     return "Falha no banco de dados. O erro foi reportado.";
    }
    
    return true;
    
    utilError:
    $this->fields[ModelCreate::$loadField]->setValid(false);
    $this->fields[ModelCreate::$stockingField]->setValid(false);
    $this->fields[ModelCreate::$modelTypeField]->setValid(false);
    return $out;
  }
}

mustBeEmployee();
correctStdFormGet();

$page = new Page("Cadastro de Modelo de Veículo");
$modelCreate = new ModelCreate();
$form = new StdForm($modelCreate, $_GET, $_POST,
        "<p>" . htmlentities("Campos em negrito são obrigatórios.") . "</p>",
        "<p>" . htmlentities("Cadastro realizado com sucesso.") . "</p>",
        "ModelCreate.php");
$form->processForm();
$page->addContent($form->getHtml());
echo $page->getHtml();
